<?php

namespace loggedin\controller;

require_once("/loggedin/model/GetQuestions.php");
require_once("/loggedin/model/Question.php");
require_once("/loggedin/view/GameView.php");

class StartGame {
	/**
	 * [$getQuestion description]
	 * @var \loggedin\model\GetQuestions
	 */
	private $getQuestion;
	/**
	 * @var \loggedin\view\GameView
	 */
	private $gameView;

	function __construct(\loggedin\view\GameView $gameView) {
		$this->getQuestion = new \loggedin\model\GetQuestions();
		$this->gameView = $gameView;
	}

	/**
	 * @return HTML string
	 */
	public function showQuestion() {
		$mysqli = new \mysqli("mysql08.citynetwork.se", "119958-mg18906",
							  "quizzer50", "119958-quizzer");
		$questionCount = $this->getQuestion->getQuestionCount($mysqli);
		$randQuestionID = rand(1, $questionCount);
		if($this->gameView->checkIfFirstQuestion()) {
			while ($randQuestionID == $this->gameView->getQuestionAnswerdID()) {
				$randQuestionID = rand(1, $questionCount);
			}
		}
		$question = $this->getQuestion->getQuestion($randQuestionID, $mysqli);
		$mysqli->close();
		$this->gameView->setQuestionAnswerdID($randQuestionID);
		return $this->gameView->questionToGameHTML($question);
	}
	
	public function correctAnswer() {
		$questionID = $this->gameView->getQuestionAnswerdID();
		$mysqli = new \mysqli("mysql08.citynetwork.se", "119958-mg18906",
							  "quizzer50", "119958-quizzer");
		$question = $this->getQuestion->getQuestion($questionID, $mysqli);
		$mysqli->close();
		$playerAnswer = $this->gameView->getAnswerdQuestionValue();
		if($playerAnswer == $question->getRightAnswer()) {
			$this->gameView->setSuccessMessage();
			$this->gameView->updatePlayerPoints(1);
		} else {
			$this->gameView->setFailMessage($question->getRightAnswer());
		}
	}
}